package com.creditease.gateway.utils;

import com.alibaba.fastjson.JSON;
import com.creditease.gateway.entity.ScheduleJobEntity;
import com.creditease.gateway.entity.ScheduleJobLogEntity;
import com.creditease.gateway.service.ScheduleJobLogService;
import org.apache.commons.lang.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

/**
 * @author liuchao
 * @email liuchao332@163.com
 * @date 2020/3/3 14:36
 */
public class ScheduleJob extends QuartzJobBean {
	private Logger logger = LoggerFactory.getLogger(getClass());

	private String url = "http://%s/%s";

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		String jsonJob = context.getMergedJobDataMap().getString(ScheduleJobEntity.JOB_PARAM_KEY);
		ScheduleJobEntity scheduleJob = JSON.parseObject(jsonJob, ScheduleJobEntity.class);

		//获取scheduleJobLogService
        ScheduleJobLogService scheduleJobLogService = (ScheduleJobLogService) SpringContextUtils.getBean("scheduleJobLogService");
        
        //数据库保存执行记录
        ScheduleJobLogEntity log = new ScheduleJobLogEntity();
        log.setJobId(scheduleJob.getJobId());
        log.setServerName(scheduleJob.getServerName());
        log.setPath(scheduleJob.getPath());
        log.setParams(scheduleJob.getParams());
        log.setCreateTime(new Date());
        log.setStatus(1);
        
        //任务开始时间
        long startTime = System.currentTimeMillis();
        
        try {
            //执行任务
        	logger.info("任务准备执行，任务ID：" + scheduleJob.getJobId());

			RestTemplate restTemplate = (RestTemplate)SpringContextUtils.getBean("restTemplate");
			String restUrl = String.format(url, scheduleJob.getServerName(), scheduleJob.getPath());
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
			headers.add("Accept", MediaType.APPLICATION_JSON.toString());
			HttpEntity<String> requestEntity = new HttpEntity<>(scheduleJob.getParams(), headers);

			ResponseEntity<String> exchange = restTemplate.exchange(restUrl, HttpMethod.POST, requestEntity, String.class);
            
			long times = System.currentTimeMillis() - startTime; //任务执行总时长
			log.setTimes((int)times);
			log.setStatus(0); //任务状态    0：成功    1：失败
			logger.info("任务执行完毕，任务ID：{} 总共耗时：{}毫秒 结果：{}", scheduleJob.getJobId(), times, exchange);
		} catch (Exception e) {
			logger.error("任务执行失败，任务ID：" + scheduleJob.getJobId(), e);
			
			//任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			log.setTimes((int)times);
			
			//任务状态    0：成功    1：失败
			log.setStatus(1);
			log.setError(StringUtils.substring(e.toString(), 0, 2000));
		}finally {
			scheduleJobLogService.save(log);
		}
    }
}
